<template>
  <ContentDetailWrap :title="t('purchase.edit')" @back="push('/purchase')">
    <Write ref="writeRef" :current-row="currentRow" :examine="true" :detail="true" />

    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
    </template>
    <!--      logisticsCosts-->
    <el-form label-width="130px">
      <el-form-item :label="t('purchase.logistics.logisticsCosts')">
        <!--      table-->
        <el-table
          :data="tableData"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'left' }"
        >
          <el-table-column :label="t('purchase.logistics.fees')">
            <template #default="{ row }">
              <el-input
                v-model="row.amount"
                type="number"
                :placeholder="t('purchase.logistics.feesPlaceholder')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('purchase.logistics.name')">
            <template #default="{ row }">
              <el-input
                v-model="row.name"
                :placeholder="t('purchase.logistics.namePlaceholder')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('purchase.logistics.orderNo')">
            <template #default="{ row }">
              <el-input
                v-model="row.order_number"
                :placeholder="t('purchase.logistics.orderNoPlaceholder')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('purchase.logistics.remark')">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                :placeholder="t('purchase.logistics.remarkPlaceholder')"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column :label="t('purchase.logistics.operation')" width="300">
            <template #default="{ row, $index }">
              <el-button type="primary" @click="handleSave(row)" class="m-r-5">
                {{ t('purchase.logistics.save') }}
              </el-button>
              <el-button type="primary" :icon="Plus" circle @click="handleAdd" class="m-r-2" />
              <el-button type="danger" :icon="Delete" circle @click="handleDelete(row, $index)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Delete, Plus } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import {
  getInfoApi,
  createLogisticsCostsApi,
  editLogisticsCostsApi,
  delLogisticsCostsApi,
  getLogisticsInfoApi
} from '@/api/purchase'
import { ElMessage, ElMessageBox } from 'element-plus'

const { push, go } = useRouter()

const { query } = useRoute()

const { t } = useI18n()

const currentRow = ref<Record<string, any>>()
const writeRef = ref<ComponentRef<typeof Write>>()

const tableData = ref<Array<Record<string, any>>>([])

const handleSave = async (row: Record<string, unknown>) => {
  if (!row.amount) return ElMessage.warning(t('purchase.logistics.feesPlaceholder'))
  if (!row.name) return ElMessage.warning(t('purchase.logistics.namePlaceholder'))
  if (!row.order_number && !row.remark)
    return ElMessage.warning(t('purchase.logistics.allValidation'))

  const resp = row.id
    ? await editLogisticsCostsApi(row.id as number, {
        purchase_order_id: query.id as string,
        ...row
      })
    : await createLogisticsCostsApi({
        purchase_order_id: query.id as string,
        ...row
      })
  if (resp.code === 0) {
    ElMessage.success(t('purchase.logistics.saveSuccess'))
    await getLogisticsList()
  }
}
const handleAdd = () => {
  tableData.value.push({
    amount: '',
    name: '',
    order_number: '',
    remark: ''
  })
}
const handleDelete = (row: Record<string, unknown>, index: number) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      if (!row.id) {
        tableData.value.splice(index, 1)
        if (!tableData.value.length) await getLogisticsList()
        return
      }
      await delLogisticsCostsApi(row.id as number, { purchase_order_id: query.id as string })
      ElMessage.success(t('purchase.logistics.deleteSuccess'))
      await getLogisticsList()
    })
    .catch(() => {})
}

const initialize = async () => {
  const res = await getInfoApi(query.id as string)
  currentRow.value = res.data
  await getLogisticsList()
}

const getLogisticsList = async () => {
  const resp = await getLogisticsInfoApi({
    purchase_order_id: query.id as string,
    from: 'logistics'
  })
  tableData.value = resp.data.list
}

onMounted(() => {
  initialize()
})
</script>
<style lang="less" scoped></style>
